//
//  MusicBeatManager.m
//  gong
//
//  Created by echo on 14-3-3.
//  Copyright (c) 2014年 echo. All rights reserved.
//

#import "MusicBeatManager.h"
#import <AVFoundation/AVFoundation.h>
#import "DanceMusic.h"
#import "UICreator.h"
#import "PositionTools.h"
#import "THProgressView.h"
#import "TTCounterLabel.h"
#import "AutoRemoveMessageView.h"
#import "StandardBeatView.h"

@interface MusicBeatManager () <AVAudioPlayerDelegate, UIAlertViewDelegate, TTCounterLabelDelegate>

@end

@implementation MusicBeatManager
{
    NSMutableArray *_danceMusicArray;
    AVAudioPlayer* _audioPlayer;
    NSInteger _currentMusicIndex;
    DanceMusic *_currentDanceMusic;
    
    NSTimer *_timer;
    UIImageView *_goodBrandImageVIew;
    __weak UIView *_container;
    
    THProgressView *_musicProgressView;
    TTCounterLabel *_counter;
    StandardBeatView *_standardBeatView;
    UIView *_flagView;
}

- (void)dealloc
{
    [self clear];
}

- (void)clear
{
    [_flagView removeFromSuperview];
    [_standardBeatView removeFromSuperview];
    [_counter removeFromSuperview];
    [_musicProgressView removeFromSuperview];
    [_goodBrandImageVIew removeFromSuperview];
    [_timer invalidate];
    [self stopMusic];
}

- (id)initWithContainer:(UIView*)container
{
    self = [super init];
    if (self) {
        _container = container;
        
        _danceMusicArray = [NSMutableArray array];
        DanceMusic *music1 = [DanceMusic new];
        DanceMusic *music2 = [DanceMusic new];
        DanceMusic *music3 = [DanceMusic new];
        
        music1.name = @"小毛驴英文";
        music1.bpm = 139.84;
        music1.beatType = TwoQuartersShot;
        
        music2.name = @"草裙舞";
        music2.bpm = 139.84;
        music2.beatType = TwoQuartersShot;
        
        music3.name = @"花仙子";
        music3.bpm = 139.84;
        music3.beatType = TwoQuartersShot;
        
        [_danceMusicArray addObject:music1];
        [_danceMusicArray addObject:music2];
        [_danceMusicArray addObject:music3];
        
        _goodBrandImageVIew = [UICreator createImageViewFromImagename:@"good.png"];
        [PositionTools placeView:_goodBrandImageVIew atTheTopMiddleOfTheView:_container offset:40];
        _goodBrandImageVIew.hidden = YES;
        
        _musicProgressView = [[THProgressView alloc] initWithFrame:CGRectMake(0, 0, _container.frame.size.width * 2 / 3, 40)];
        _musicProgressView.borderTintColor = [UIColor whiteColor];
        _musicProgressView.progressTintColor = [UIColor whiteColor];
        _musicProgressView.progress = 0;
        _musicProgressView.hidden = YES;
        
        [PositionTools placeView:_musicProgressView atTheTopMiddleOfTheView:_container offset:40];
    }
    
    return self;
}

- (void)play:(NSString*)musicName preListen:(BOOL)isPrelisten
{
    if (isPrelisten) {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
        
        NSString *soundFilePath =[[NSBundle mainBundle] pathForResource:musicName
                                                                 ofType: @"mp3"];
        
        NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
        
        [_audioPlayer stop];
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];
        _audioPlayer.volume = 1;
        
        _currentDanceMusic.duration = _audioPlayer.duration;
        [_currentDanceMusic calculateBeatPostions];
    }
    
    [_audioPlayer prepareToPlay];
    
    if (!isPrelisten) {
        _audioPlayer.delegate = self;
        _timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(checkBeat) userInfo:nil repeats:YES];
        _musicProgressView.hidden = NO;
    }
    
    [_audioPlayer play];
    
}

- (void)stop
{
    [_audioPlayer stop];
    [_timer invalidate];
}

- (void)checkBeat
{
    //    NSLog(@"=========currentTime is %f", _audioPlayer.currentTime);
    _goodBrandImageVIew.hidden = YES;
    CGFloat progress = _audioPlayer.currentTime / _audioPlayer.duration;
    [_musicProgressView setProgress:progress animated:YES];

    NSLog(@"current time is %f", _audioPlayer.currentTime);
    float positionScale = _audioPlayer.currentTime / _audioPlayer.duration;
    float beatX = _container.frame.size.width/2 + _standardBeatView.frame.size.width/2 + positionScale * (- _standardBeatView.frame.size.width);
    _standardBeatView.center = CGPointMake(beatX, _standardBeatView.center.y);
}

- (void)checkTouch
{
    //    NSLog(@"=========currentTime is %f", _audioPlayer.currentTime);
    
    NSInteger ret = [_currentDanceMusic evalue:_audioPlayer.currentTime];
    if (1 ==ret) {
//        _goodBrandImageVIew.hidden = NO;
        [AutoRemoveMessageView show:@"干的漂亮" withContainerView:_container duration:.1 completion:nil];
    } else if (2 == ret) {
        [AutoRemoveMessageView show:@"还不错啦" withContainerView:_container duration:.1 completion:nil];
    } else if (3 == ret) {
        [AutoRemoveMessageView show:@"马马虎虎" withContainerView:_container duration:.1 completion:nil];
    } else {
        [AutoRemoveMessageView show:@"还需要努力哟" withContainerView:_container duration:.1 completion:nil];
    }
}

- (void)playMusic
{
    if (_currentMusicIndex >= 0 && _currentMusicIndex < _danceMusicArray.count) {
        _currentDanceMusic = _danceMusicArray[_currentMusicIndex];
        
        [self play:_currentDanceMusic.name preListen:YES];
        
        [[[UIAlertView alloc] initWithTitle:@"提示" message:@"现在是预听阶段，点击开始按钮开始游戏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"开始", nil] show];
        
        //        _currentMusicIndex++;
        //        if (_currentMusicIndex > _danceMusicArray.count) {
        //            _currentMusicIndex = 0;
        //        }
    }
}

- (void)stopMusic
{
    [_audioPlayer stop];
}

- (void)startGame
{
    _currentMusicIndex++;
    if (_currentMusicIndex > _danceMusicArray.count) {
        _currentMusicIndex = 0;
    }
    
    _standardBeatView = [[StandardBeatView alloc] initWithFrame:CGRectMake(0, 0, _container.frame.size.width/2, 40)];
    [PositionTools placeView:_standardBeatView atTheTopMiddleOfTheView:_container offset:200];
    
    [_standardBeatView drawStandardBeat:_currentDanceMusic];
    [self play:_currentDanceMusic.name preListen:NO];
    
    if (!_flagView) {
        _flagView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _currentDanceMusic.checkTimeSpan * 100, _container.frame.size.height)];
        _flagView.backgroundColor = [UIColor greenColor];
        [PositionTools placeView:_flagView atTheCenterOfTheView:_container];
    }
    
    [PositionTools placeView:_standardBeatView atTheLeftTopOfTheView:_container offset:CGSizeMake(_container.frame.size.width/2, 200)];
}

#pragma mark - AVAudioPlayerDelegate

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [_standardBeatView removeFromSuperview];
    [_flagView removeFromSuperview];
    
    NSLog(@"final score is %i", [_currentDanceMusic getScore]);
    NSString *msg = [NSString stringWithFormat:@"你得了%i分", [_currentDanceMusic getScore]];
    [[[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [_audioPlayer stop];
    
    if (0 == buttonIndex) {
        
    } else if (1 == buttonIndex) {
        _counter = [[TTCounterLabel alloc] initWithFrame:CGRectMake(0, 0, 100, 80)];
        [PositionTools placeView:_counter atTheCenterOfTheView:_container];
        
        _counter.countdownDelegate = self;
        
        [_counter setBoldFont:[UIFont fontWithName:@"HelveticaNeue-Medium" size:55]];
        [_counter setRegularFont:[UIFont fontWithName:@"HelveticaNeue-UltraLight" size:55]];
        
        // The font property of the label is used as the font for H,M,S and MS
        [_counter setFont:[UIFont fontWithName:@"HelveticaNeue-UltraLight" size:25]];
        
        // Default label properties
        _counter.textColor = [UIColor darkGrayColor];
        
        _counter.startValue = 3000;
        _counter.countDirection = kCountDirectionDown;
        //    _counter.currentValue = 1000000;
        
        // After making any changes we need to call update appearance
        [_counter updateApperance];
        
        [_counter start];
        
    }
}

#pragma mark - TTCounterLabelDelegate

- (void)countdownDidEnd
{
    [_counter removeFromSuperview];
    [AutoRemoveMessageView show:@"Let's GO!!!" withContainerView:_container duration:1 completion:^{
        [self startGame];
    }];
}

@end
